package com.news.controller;

import com.news.config.Constant;
import com.news.model.ImageEntity;
import com.news.service.ImageService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * Created by lingzhiyuan.
 * Date : 15/8/29.
 * Time : 下午6:49.
 * Description:
 */
@Controller
@RequestMapping("/image")
public class ImageController {

    @Resource
    private ImageService imageService;

    @RequestMapping("/upload")
    @ResponseBody
    public Object uploadImage(@RequestParam(required = true)MultipartFile imageFile){

        ImageEntity image = imageService.uploadImage(imageFile);
        return image;
    }

    @RequestMapping("/list")
    @ResponseBody
    public Object listAllImages(@RequestParam(required = false,defaultValue = "10")int page_size,
                                @RequestParam(required = false,defaultValue = "1")int page_num){
        Map result = imageService.listImages(page_size,page_num);
        List<ImageEntity> images = (List<ImageEntity>) result.get("images");
        for (ImageEntity image : images){
            String url = image.getUrl();
            if (url != null){
                if (!url.startsWith("http")){
                    image.setUrl(Constant.BASE_URL+url);
                }
            }
        }
        result.put("images",images);
        return result;
    }

}
